<template>
  <div>
    <!-- 上传 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :class="{ disabled: fileList.length > 0 }"
      :file-list="fileList"
      :on-preview="preview"
      :on-remove="del"
      :on-change="change"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="showPercentage" :text-inside="true" :stroke-width="26" :percentage="percentage" style="width:146px" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDCE0VjgMmvoRnreBSR9akeGbgU3LM6Zke',
  SecretKey: 'f39yXqse9NL3UfZBWbPwCBtKUNzKPDk1'
})
export default {
  data() {
    return {
      showDialog: false,
      showPercentage: false,
      imgUrl: '',
      percentage: 0,
      fileList: []
    }
  },
  methods: {
    // 图片上传是的钩子函数
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 删除图片
    del(file, fileList) {
      this.fileList = fileList
    },
    // 上传改变时触发
    change(file, fileList) {
      this.fileList = fileList
    },
    // http-request覆盖默认上传
    upload(params) {
      this.showPercentage = true
      cos.putObject(
        {
          Bucket: 'hrsaas-1307451473' /* 必须 储存桶名称*/,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: params.file.name /* 必须 储存文件名*/,
          StorageClass: 'STANDARD', // 储存类型
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
          }
        },
        (err, data) => {
          console.log(err || data)
          if (!err) {
            this.fileList[0].url = `http://${data.Location}`
            this.fileList[0].status = 'success'
          }
          setTimeout(() => {
            this.showPercentage = false
          }, 1000)
        }
      )
    },
    // before-upload 上传文件之前的钩子函数
    beforeUpload(file) {
      console.log(file)
      const maxsize = 2 * 1024 * 1024
      if (file.size > maxsize) {
        this.$message.warning('图片只支持2M以内')
        return false
      }

      const wList = ['image/jpeg', 'image/png']
      if (!wList.includes(file.type)) {
        this.$message.warning('当前只支持jpeg/png格式')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
